package cn.jvtc.course.management.system.utils;

import java.sql.*;
import java.util.Properties;

/**
 * jdbc工具类，用于获取数据库连接，关闭连接等操作
 *
 * @author GaoFeng2017
 * @date 2017-12-11 09:01:46
 **/

public class JdbcUtils {
    private static Properties config = new Properties();

    /*加载并注册驱动*/
    static {
        try {
            config.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));
            Class.forName(config.getProperty("driver"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @description:获取数据库连接
     * @author: GaoFeng2017
     * @date: 2017/12/11 9:52
     * @param: []
     * @return: java.sql.Connection
     *
     */
    public static Connection getConnection() throws SQLException {

        Connection con = DriverManager.getConnection(config.getProperty("url"), config.getProperty("user"),config.getProperty("password"));
        return con;
    }

    /**
     * @description:释放jdbc连接资源
     * @author: GaoFeng2017
     * @date: 2017/12/11 9:53
     * @param: [con, st, rs]
     * @return: void
     *
     */
    public static void releaseResource(Connection con, Statement st,ResultSet rs) {

        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
            }
        }


        if(st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                con = null;
            }
        }

    }
}
